<template>
  <div class="chat-interface">
    <!-- 消息列表 - 固定高度，可滚动 -->
    <div class="messages-container" ref="messagesContainer">
      <div class="messages-wrapper">
        <div v-if="chatList.length === 0" class="empty-state">
          <!-- 主标题 -->
          <div class="welcome-section">
            <div class="text-gray-400 mb-6">
              <svg class="w-20 h-20 mx-auto" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" clip-rule="evenodd" />
              </svg>
            </div>
            <h1 class="text-2xl font-bold text-gray-800 mb-3">我是电价政策智能助手，很高兴见到你</h1>
            <p class="text-gray-600 mb-8 text-lg">我可以帮助你查询电价政策，解答你的疑问。</p>
          </div>

          <!-- 猜你想问 -->
          <div class="suggested-questions-section">
            <h3 class="text-lg font-semibold text-gray-700 mb-4">猜你想问</h3>
            <div class="questions-grid">
              <button
                v-for="question in defaultQuestions"
                :key="question"
                @click="handleQuestionClick(question)"
                class="question-card"
              >
                {{ question }}
              </button>
            </div>
          </div>
        </div>

        <div v-else class="chat-messages">
          <ChatMessage
            v-for="message in chatList"
            :key="message.id"
            :message="message"
            :feedback-disabled="feedbackDisabled"
            @copy="handleCopy"
            @regenerate="handleRegenerate"
            @feedback="handleFeedback"
            @suggest-question="handleSuggestQuestion"
          />
          
        </div>
      </div>
    </div>

    <!-- 输入区域 - 固定在底部 -->
    <div class="input-container">
      <ChatInput
        :loading="isResponding"
        :disabled="feedbackDisabled"
        :control-clear="controlClearQuery"
        @send="handleSend"
        @stop="handleStop"
      />
    </div>

    <!-- 悬浮建议问题 -->
    <SuggestedQuestions
      :questions="suggestedQuestions"
      :visible="showSuggestedQuestions"
      :loading="loadingSuggestions"
      @question-click="handleSuggestedQuestionClick"
      @close="handleCloseSuggestions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, computed } from 'vue'
import { useToast } from 'vue-toast-notification'
import ChatMessage from './ChatMessage.vue'
import ChatInput from './ChatInput.vue'
import SuggestedQuestions from './SuggestedQuestions.vue'
import { getSuggestedQuestions } from '@/service'
import type { ChatItem, Feedbacktype, VisionFile, VisionSettings } from '@/types/app'

interface Props {
  chatList: ChatItem[]
  isResponding: boolean
  feedbackDisabled: boolean
  visionConfig?: VisionSettings
  controlClearQuery?: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  send: [message: string, files: VisionFile[]]
  feedback: [messageId: string, feedback: Feedbacktype]
  stop: []
  regenerate: [messageId: string]
}>()

const messagesContainer = ref<HTMLElement>()
const toast = useToast()

// 默认问题列表
const defaultQuestions = [
  '2018年集中式光伏电站标杆上网电价如何调整？',
  '分布式光伏发电的电价补贴标准是多少？如何执行？',
  '山西省如何简化上网电价管理？',
  '如何加强对建筑屋顶资源利用的统筹协调？',
  '山西省发电机组进入商业运营需满足哪些条件？'
]

// 建议问题相关状态
const suggestedQuestions = ref<string[]>([])
const showSuggestedQuestions = ref(false)
const loadingSuggestions = ref(false)
const lastProcessedMessageId = ref<string>('')

// 计算最后一条AI消息
const lastAiMessage = computed(() => {
  const aiMessages = props.chatList.filter(msg => msg.isAnswer && !msg.streaming)
  return aiMessages.length > 0 ? aiMessages[aiMessages.length - 1] : null
})

const handleSend = (message: string, files: File[]) => {
  const visionFiles: VisionFile[] = files.map(file => ({
    type: file.type,
    url: URL.createObjectURL(file),
    upload_file_id: `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }))
  
  // 发送消息时隐藏建议问题
  hideSuggestedQuestions()
  
  emit('send', message, visionFiles)
}

const handleCopy = (content: string) => {
  navigator.clipboard.writeText(content).then(() => {
    toast.success('消息已复制到剪贴板')
  }).catch(error => {
    console.error('复制失败:', error)
    toast.error('复制失败')
  })
}

const handleRegenerate = (messageId: string) => {
  // 重新生成时隐藏建议问题
  hideSuggestedQuestions()
  
  console.log('重新生成消息:', messageId)
  toast.info('正在重新生成回答...')
  
  // 发出重新生成事件给父组件
  emit('regenerate', messageId)
}

const handleFeedback = (messageId: string, feedback: Feedbacktype) => {
  emit('feedback', messageId, feedback)
  toast.success(feedback.rating === 'like' ? '感谢您的正面反馈！' : '感谢您的反馈，我们会努力改进！')
}

const handleSuggestQuestion = (question: string) => {
  // 处理消息内的建议问题点击
  console.log('消息内建议问题:', question)
  
  // 隐藏悬浮建议问题
  hideSuggestedQuestions()
  
  // 发送问题
  emit('send', question, [])
}

const handleSuggestedQuestionClick = (question: string) => {
  // 处理悬浮建议问题点击
  console.log('悬浮建议问题点击:', question)
  
  // 隐藏建议问题
  hideSuggestedQuestions()
  
  // 发送问题
  emit('send', question, [])
}

const handleCloseSuggestions = () => {
  hideSuggestedQuestions()
}

const handleStop = () => {
  emit('stop')
}

// 处理默认问题点击
const handleQuestionClick = (question: string) => {
  console.log('默认问题点击:', question)
  emit('send', question, [])
}

// 获取建议问题
const fetchSuggestedQuestions = async (messageId: string) => {
  if (!messageId || messageId === lastProcessedMessageId.value) {
    return
  }

  try {
    console.log('🔍 获取建议问题，消息ID:', messageId)
    loadingSuggestions.value = true
    
    const response = await getSuggestedQuestions(messageId)
    console.log('📝 建议问题API响应:', response)
    
    // 处理API响应
    let questions: string[] = []
    if (Array.isArray(response)) {
      questions = response
    } else if (response && typeof response === 'object') {
      if ('data' in response && Array.isArray(response.data)) {
        questions = response.data
      } else if ('questions' in response && Array.isArray(response.questions)) {
        questions = response.questions
      } else if ('suggested_questions' in response && Array.isArray(response.suggested_questions)) {
        questions = response.suggested_questions
      }
    }
    
    console.log('✅ 处理后的建议问题:', questions)
    
    if (questions.length > 0) {
      suggestedQuestions.value = questions
      showSuggestedQuestions.value = true
      lastProcessedMessageId.value = messageId
      
      toast.success(`获取到 ${questions.length} 个建议问题`)
    } else {
      console.log('⚠️ 没有获取到建议问题')
    }
    
  } catch (error) {
    console.error('❌ 获取建议问题失败:', error)
    toast.error('获取建议问题失败')
  } finally {
    loadingSuggestions.value = false
  }
}

// 隐藏建议问题
const hideSuggestedQuestions = () => {
  showSuggestedQuestions.value = false
  suggestedQuestions.value = []
}

// 自动滚动到底部
const scrollToBottom = (smooth = true) => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: smooth ? 'smooth' : 'auto'
      })
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(() => props.chatList, (newList, oldList) => {
  console.log(`ChatInterface - 消息列表更新: ${oldList?.length || 0} -> ${newList.length}`)
  
  // 检查是否为流式更新（内容变化但消息数量不变）
  const isStreamingUpdate = oldList && newList.length === oldList.length && 
    newList.some((msg, index) => {
      const oldMsg = oldList[index]
      return oldMsg && (
        msg.content !== oldMsg.content || 
        msg.streaming !== oldMsg.streaming ||
        msg.lastUpdated !== oldMsg.lastUpdated
      )
    })
  
  // 如果是流式更新，记录详细信息
  if (isStreamingUpdate) {
    const streamingMessages = newList.filter(msg => msg.streaming)
    console.log('检测到流式更新:', {
      streamingCount: streamingMessages.length,
      messages: streamingMessages.map(msg => ({
        id: msg.id,
        contentLength: msg.content?.length || 0,
        streaming: msg.streaming,
        lastUpdated: msg.lastUpdated
      }))
    })
  }
  
  // 流式更新时使用平滑滚动，新消息时立即滚动
  scrollToBottom(!isStreamingUpdate)
}, { deep: true, immediate: false })

// 监听响应状态变化
watch(() => props.isResponding, (isResponding, wasResponding) => {
  if (isResponding) {
    // 开始响应时隐藏建议问题
    hideSuggestedQuestions()
    scrollToBottom()
  } else if (wasResponding && !isResponding) {
    // 响应结束时，获取建议问题
    console.log('🎯 AI响应结束，准备获取建议问题')
    
    // 延迟一下确保消息已经完全更新
    setTimeout(() => {
      const lastMessage = lastAiMessage.value
      if (lastMessage && lastMessage.id) {
        console.log('📋 最后一条AI消息:', lastMessage.id)
        fetchSuggestedQuestions(lastMessage.id)
      } else {
        console.log('⚠️ 没有找到最后一条AI消息')
      }
    }, 500)
  }
})

// // 监听最后一条AI消息的变化
// watch(lastAiMessage, (newMessage, oldMessage) => {
//   // 如果有新的AI消息且不在响应中，获取建议问题
//   if (newMessage && 
//       newMessage.id !== oldMessage?.id && 
//       !props.isResponding && 
//       !newMessage.streaming) {
//     console.log('🆕 检测到新的AI消息完成:', newMessage.id)
//     fetchSuggestedQuestions(newMessage.id)
//   }
// })
</script>

<style scoped>
.chat-interface {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  /* 确保背景覆盖 */
  background: inherit;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20px;
  /* 防止滚动穿透和白边 */
  position: relative;
  background: linear-gradient(to bottom, #f8fafc 0%, #f1f5f9 100%);
  /* iOS Safari优化 */
  -webkit-overflow-scrolling: touch;
  /* 防止橡皮筋效果 */
  overscroll-behavior: contain;
}

.messages-wrapper {
  max-width: 950px;
  margin: 0 auto;
  padding: 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  text-align: center;
  padding: 48px 20px;
}

.welcome-section {
  margin-bottom: 40px;
}

.suggested-questions-section {
  width: 100%;
  max-width: 600px;
}

.questions-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin-top: 16px;
}

.question-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px 20px;
  text-align: left;
  color: #374151;
  font-size: 14px;
  line-height: 1.5;
  transition: all 0.2s ease;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.question-card:hover {
  background: #f8fafc;
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
}

.question-card:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.input-container {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: transparent;
  border: none;
  z-index: 10;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

@keyframes fadeIn {
  from { 
    opacity: 0; 
    transform: translateY(10px); 
  }
  to { 
    opacity: 1; 
    transform: translateY(0); 
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-wrapper {
    max-width: none;
    padding: 16px;
  }
  
  .empty-state {
    min-height: 50vh;
    padding: 32px 16px;
  }
  
  .welcome-section h1 {
    font-size: 1.5rem;
  }
  
  .welcome-section p {
    font-size: 1rem;
  }
  
  .suggested-questions-section {
    max-width: none;
  }
  
  .question-card {
    padding: 14px 16px;
    font-size: 13px;
  }
  
  .typing-wrapper {
    max-width: none;
  }
  
  .typing-bubble {
    border-radius: 16px;
    padding: 12px 16px;
  }
}
</style> 